#include <mysql/mysql.h>
#include <iostream>

static const char *host = "127.0.0.1";
static const char *user = "ly";
static const char *passwd = "20020214";
static const char *db = "test_db";
static unsigned int port = 3306;
int main()
{
    MYSQL *my = mysql_init(nullptr);// 初始化
    my = mysql_real_connect(my,host,user,passwd,db,port,nullptr,0);// 连接数据库
    if(my == nullptr)
    {
        std::cerr << "connect mysql failed!" << std::endl;
        return 1;
    }
    // 连接数据库成功
    int n = mysql_set_character_set(my,"utf8");
    if(n != 0)
    {
        std::cerr << "设置字符集失败!" << std::endl;
        return 2;
    }
    // const char *sql = "insert into user (name,age,tel) values('李四',26,'13077315578')";
    // const char *sql = "delete from user where id=1";
    // const char *sql = "update user set age=21 where id=2";
    const char *sql = "select * from user";
    n = mysql_query(my,sql);
    if(n != 0)
    {
        std::cerr << "执行sql语句失败!" << std::endl;
        return 3;
    }
    MYSQL_RES *res = mysql_store_result(my);// 得到结果集
    my_ulonglong row_num = mysql_num_rows(res);// 得到结果行数
    my_ulonglong fields_num = mysql_num_fields(res);// 得到结果列数
    std::cout << "行数: " << row_num << std::endl;
    std::cout << "列数: " << fields_num << std::endl;

    MYSQL_FIELD *field = mysql_fetch_field(res);// 获取列
    for(int i=0;i<fields_num;i++)
    {
        std::cout << field[i].name << "\t";
    }
    std::cout << std::endl;

    for(int i=0;i<row_num;i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);// 获取每行
        for(int j=0;j<fields_num;j++)
        {
            std::cout << row[j] << "\t";
        }
        std::cout << std::endl;
    }
    mysql_free_result(res);// 关闭结果集
    mysql_close(my);// 关闭句柄
    return 0;
}